﻿using AIVision.Model.EntityModels;
using AIVision.Repository.Entitys;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIVision.Repository.Services
{
    public class CameraService
    {
        private readonly AiVisionDbContext dbContext;
        private readonly IMapper mapper;

        public CameraService(AiVisionDbContext dbContext, IMapper mapper)
        {
            this.dbContext = dbContext;
            this.mapper = mapper;
        }

        public List<CameraDto> GetAllCameras()
        {
            List<CameraDto> result = new List<CameraDto>();
            foreach (var item in dbContext.Cameras)
            {
                result.Add(mapper.Map<CameraDto>(item));
            }
            return result;
        }

        public void SaveCameras(List<CameraDto> cameras)
        {
            foreach (var item in cameras)
            {

                var newentity = mapper.Map<Camera>(item);

                var entity = dbContext.Cameras.FirstOrDefault(m => m.Id == item.Id);
                if (entity != null)
                    dbContext.Entry(entity).CurrentValues.SetValues(newentity);
                else
                    dbContext.Cameras.Add(newentity);
            }
            dbContext.SaveChanges();
        }

        public void DeleteCamera(CameraDto camera)
        {
            var entity = dbContext.Cameras.FirstOrDefault(m => m.Id == camera.Id);
            if (entity != null)
            {
                dbContext.Cameras.Remove(entity);
                dbContext.SaveChanges();
            }
        }
    }
}
